/**
 * 
 */
package test.serializable ;

import java.io.IOException ;
import java.io.ObjectInputStream ;
import java.io.ObjectOutputStream ;
import java.io.Serializable ;

/**
 * 因为序列化可以构造一个对象，因此是生成类的一种方式，那么这不也破坏了对象的单利需求么 这个例子是在满足序列化的同时不破坏单利的demo
 * @author 80002165 @date 2017年3月31日 下午5:49:40
 */
public class SinglerSerializableDemo implements Serializable {
    private static final long serialVersionUID = 1722470140177580742L ;
    private String name ;
    private int age ;
    
    private SinglerSerializableDemo(String name, int age) {
        this.name = name ;
        this.age = age ;
    } ;
    
    static class SinglerHandler {
        private final static SinglerSerializableDemo singler = new SinglerSerializableDemo("方书豪", 26) ;
    }
    
    public static SinglerSerializableDemo getInstance() {
        return SinglerHandler.singler ;
    }
    
    private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException{
        stream.defaultReadObject();
        this.name = stream.readUTF() ;
        this.age = 18 ;
        System.out.println("personality read object success !") ;
    }
    
    private void writeObject(ObjectOutputStream stream) throws IOException{
        stream.defaultWriteObject(); 
        stream.writeUTF(this.name);
        System.out.println("personality write object success!") ;
    }
    
    private Object writeReplace(){
        System.out.println("writeReplace !") ;
        return new SinglerSerializableDemo("大力水手", 500) ;
    }
    
    private Object readResolve(){
        System.out.println("readResolve !") ;
        return SinglerHandler.singler ;
    }
    
    @Override
    public String toString() {
        return "my name is:"+name+", and my age is:"+age ;
    }
    
    public static void main(String[] args) throws ClassNotFoundException, IOException {
        SinglerSerializableDemo demo = getInstance() ;
        SerializableUtils.writeToFile(demo, "SinglerSerializableDemo.ser"); 
        Object readObj = SerializableUtils.readFromFile("SinglerSerializableDemo.ser") ;
        System.out.println(readObj) ;
        System.out.println(demo == readObj) ;
        /*
         * 
            writeReplace ! 
            personality write object success!
            personality read object success !
            readResolve !
            my name is:方书豪, and my age is:26
            true
         */
    }
}
